package com.atguigu.gulimall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @DESCRIPTION: feign 配置
 * @author: zr
 * @DATE: 2023/3/9 22:48
 */
@Configuration
@Slf4j
public class GuliFeignConfig {
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            // 通过RequestContextHolder 拿到老请求
            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            log.info("feign远程调用之前先进行RequestInterceptor.applyservletRequestAttributes{}",servletRequestAttributes);
            if (servletRequestAttributes!=null){
                // 无需共享数据就不用做以下操作了
                HttpServletRequest oldRequest = servletRequestAttributes.getRequest();
                // 同步请求头数据
                if (oldRequest!=null){
                    String cookie = oldRequest.getHeader("Cookie");
                    requestTemplate.header("Cookie",cookie);
                }
            }
        };
    }

}
